package com.viphuli.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.offroader.utils.JsonUtils;
import com.offroader.utils.StringUtils;
import com.offroader.utils.ViewUtils;
import com.viphuli.adapter.TicketAdapter;
import com.viphuli.app.R;
import com.viphuli.common.AccessTokenKeeper;
import com.viphuli.http.ApiRequest;
import com.viphuli.http.bean.PageBaseBean;
import com.viphuli.http.bean.part.PurchasePayTicket;
import com.viphuli.http.handler.MyBaseHttpResponseHandler.HandlerType;

/**
 * 代金卷
 * 
 * @author li.li
 *
 */
public class AccountTicketFragment extends BaseProgressFragment implements OnItemClickListener {
	public static final String KEY_PAY_SELECTED_TICKET = "pay_selected_ticket";

	@Bind(R.id.layout_ticket_listview)
	protected ListView listView;

	@Bind(R.id.id_account_ticket_top_vcode_layout)
	protected ViewGroup vCodeLayout;

	@Bind(R.id.id_account_ticket_top_vcode_text)
	protected EditText vCodeText;

	@Bind(R.id.id_account_ticket_top_vcode_btn)
	protected TextView vCodeBtn;

	@Bind(R.id.ticket_empty)
	protected View empty;

	private BaseAdapter adapter;

	private List<PurchasePayTicket> list = new ArrayList<PurchasePayTicket>();
	private boolean isFromPay;

	@Override
	protected int obtainContentRes() {
		return R.layout.frag_account_ticket;
	}

	@Override
	protected void initParams() {
		//解析参数
		Bundle args = getArguments();
		String ticketsJson = args.getString("tickets");

		if (StringUtils.isNotBlank(ticketsJson)) {
			isFromPay = true;
			Type type = new TypeToken<List<PurchasePayTicket>>() {
			}.getType();
			List<PurchasePayTicket> tickets = JsonUtils.fromJson(ticketsJson, type);
			list.addAll(tickets);
		} else {
			isFromPay = false;
		}
	}

	@Override
	protected void initView() {
		setCanLoadMore(false);

		listView.setOnItemClickListener(this);
	}

	@Override
	protected void initData() {

		if (isFromPay) {

			TicketAdapter adapter = new TicketAdapter(this, list);
			listView.setAdapter(adapter);
			vCodeLayout.setVisibility(View.GONE);

		} else {

			requestData();
		}

	}

	private void requestData() {
		initRequest(HandlerType.loading);

	}

	@Override
	protected void initRequest(HandlerType handlerType) {
		list.clear();

		//网络请求
		AccessTokenKeeper token = AccessTokenKeeper.readAccessToken(getActivity());

		if (token.isLogin()) {

			RequestParams params = new RequestParams();
			params.put("uid", token.getOpenId());

			ApiRequest.accountConsumeTicket.request(this, params, handlerType);

		} else {
			AccountLoginFragment.goWithConfirmResult(getActivity(), getActivity().getString(R.string.tip_need_login));
		}

	}

	@OnClick(R.id.id_account_ticket_top_vcode_btn)
	public void ticketExchange() {

		String code = vCodeText.getText().toString();

		if (StringUtils.isBlank(code)) {
			ViewUtils.toast(R.string.tip_exchange_code);
			return;
		}

		//网络请求
		AccessTokenKeeper token = AccessTokenKeeper.readAccessToken(getActivity());

		if (token.isLogin()) {

			RequestParams params = new RequestParams();
			params.put("uid", token.getOpenId());
			params.put("exchange_code", code);

			ApiRequest.accountConsumeTicketExchange.request(this, params);

		} else {
			AccountLoginFragment.goWithConfirm(getActivity());
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getActivity().getMenuInflater().inflate(R.menu.menu_account_ticket, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (R.id.id_menu_account_ticket_right == item.getItemId()) {
			ApiRequest.accountUserConsumeTicketInstructions.request(getActivity());
			return true;
		}

		return false;
	}

	public ListView getListView() {
		return listView;
	}

	public List<PurchasePayTicket> getList() {
		return list;
	}

	public void setBaseAdapter(BaseAdapter adapter) {
		this.adapter = adapter;
	}

	public BaseAdapter getBaseAdapter() {
		return adapter;
	}

	public View getEmpty() {
		return empty;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		PurchasePayTicket ticket = list.get(position);
		setResultAndFinish(ticket);
	}

	/**
	 * 设置结果并结束
	 * @param localName
	 * @param address
	 */
	private void setResultAndFinish(PurchasePayTicket ticket) {

		Intent intent = new Intent();
		intent.putExtra(KEY_PAY_SELECTED_TICKET, ticket != null ? JsonUtils.toJson(ticket) : null);
		caller.setResult(Activity.RESULT_OK, intent);
		caller.finish();

	}

	@Override
	public void onRequestResonse(PageBaseBean page) {
		super.onRequestResonse(page);

		if (page.isSuccess()) {
			requestData();
		}
	}

}
